[EXPERIMENT] System.Text.Json: Performance optimizations for hot paths#2
Open
[EXPERIMENT] System.Text.Json: Performance optimizations for hot paths#2
Conversation
- Replace IntegerRegex with manual char scanning in enum parsing for faster integer detection in TryParseEnumFromString - Add AggressiveInlining to ValidateWritingValue and SetFlagToAddListSeparatorBeforeNextItem in Utf8JsonWriter (called on every value write) - Replace Delimiters.Contains() linear search with inline IsDelimiter() switch in number parsing hot paths (Utf8JsonReader and MultiSegment) - Replace EscapableChars.IndexOf() linear search with inline IsEscapableChar() switch in string escape validation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Owner
Author
|
@EgorBot -intel -arm using BenchmarkDotNet.Attributes;
using System.Text.Json;
using System.Text.Json.Serialization;
public class StjPerfValidation
{
private byte[] _smallJson;
private byte[] _nestedJson;
private JsonSerializerOptions _options;
public enum Color { Red, Green, Blue, Yellow, Cyan, Magenta, White, Black }
public class SmallPoco
{
public int Id { get; set; }
public string Name { get; set; }
public bool Active { get; set; }
public double Score { get; set; }
}
[GlobalSetup]
public void Setup()
{
_smallJson = JsonSerializer.SerializeToUtf8Bytes(new SmallPoco { Id = 42, Name = "test", Active = true, Score = 3.14 });
_nestedJson = JsonSerializer.SerializeToUtf8Bytes(new { a = new { b = 1, c = "hello" }, d = new[] { 1, 2, 3 }, e = true, f = 0.0 });
_options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } };
}
[Benchmark]
public SmallPoco Deserialize_SmallPoco() => JsonSerializer.Deserialize<SmallPoco>(_smallJson);
[Benchmark]
public void Reader_TokenScan()
{
var reader = new Utf8JsonReader(_nestedJson);
while (reader.Read()) { }
}
[Benchmark]
public byte[] Serialize_SmallPoco() => JsonSerializer.SerializeToUtf8Bytes(new SmallPoco { Id = 42, Name = "test", Active = true, Score = 3.14 });
[Benchmark]
public Color Deserialize_Enum() => JsonSerializer.Deserialize<Color>("\"Blue\"", _options);
[Benchmark]
public string Serialize_Enum() => JsonSerializer.Serialize(Color.Green, _options);
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This is an experimental performance exploration PR. The changes here are speculative optimizations generated from a comprehensive AI-assisted performance audit and need to be validated with benchmarks before being considered for any real PR.
Changes
Reader: Inline delimiter/escape checks — Replace
Delimiters.Contains()(8-byte span scan) withIsDelimiter()switch expression in 5 hot-path call sites acrossUtf8JsonReaderandUtf8JsonReader.MultiSegment. Same forEscapableChars.IndexOf()→IsEscapableChar()(3 call sites).Writer: AggressiveInlining — Add
[MethodImpl(MethodImplOptions.AggressiveInlining)]toValidateWritingValue()andSetFlagToAddListSeparatorBeforeNextItem(), called on every write operation.Enum converter: Regex → manual char scan — Replace
JsonHelpers.IntegerRegex.IsMatch()with a simpleIsIntegerLike()loop inEnumConverter, avoiding regex engine overhead on enum deserialization cache misses.Validation
Questions for reviewers
Full audit report: https://gist.github.com/artl93/8f375461b1a29d48b26053b88db76058